#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
删除所有Java文件中的注释，确保UTF-8编码
"""
import os
import re
import chardet
from pathlib import Path

def fix_file_comments(file_path):
    """
    删除文件中的所有注释并确保UTF-8编码
    """
    try:
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            
        # 检测编码
        detected = chardet.detect(raw_data)
        encoding = detected['encoding']
        
        # 尝试解码
        try:
            content = raw_data.decode(encoding or 'utf-8')
        except:
            content = raw_data.decode('utf-8', errors='replace')
        
        # 删除所有注释
        # 单行注释
        content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)
        # 多行注释
        content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL | re.MULTILINE)
        
        # 清理多余的空行
        content = re.sub(r'\n\s*\n', '\n\n', content)
        
        # 确保文件以换行符结束
        if content and not content.endswith('\n'):
            content += '\n'
        
        # 以UTF-8编码写回文件
        with open(file_path, 'w', encoding='utf-8', newline='\n') as f:
            f.write(content)
            
        return True
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")
        return False

def find_java_files(directory):
    """查找所有Java文件"""
    java_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def main():
    """主函数"""
    print("删除所有Java文件中的注释并确保UTF-8编码...")
    
    java_last_war_dir = Path(__file__).parent.parent.parent
    java_files = find_java_files(java_last_war_dir)
    
    print(f"找到 {len(java_files)} 个Java文件")
    
    fixed_count = 0
    failed_count = 0
    
    for file_path in java_files:
        relative_path = os.path.relpath(file_path, java_last_war_dir)
        print(f"处理: {relative_path}")
        
        if fix_file_comments(file_path):
            fixed_count += 1
        else:
            failed_count += 1
    
    print(f"\n处理完成:")
    print(f"成功修复: {fixed_count} 个文件")
    print(f"失败: {failed_count} 个文件")

if __name__ == "__main__":
    main()